#! /usr/bin/env python
#coding=utf-8
#originated  from http://code.google.com/p/pyweblog
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
import web
from google.appengine.api import users
from utils import safeint
#from isodate import parse_iso
import models

__all__ = ['dispatcher']


def _check(username, password):
    if not models.RpcUser.check_api_user_pass(username, password):
        raise Exception('access denied')


def blogger_getUsersBlogs(appkey, username, password):
    _check(username, password)
    return [{'url' : 'http://' + web.ctx.host, 'blogid' : 'tublog_001', 'blogName' : models.get_blog_config().title}]


def blogger_deletePost(appkey, postid, username, password, publish):
    _check(username, password)
    r = models.Entry.del_by_index(safeint(postid))
    return bool(r)


def metaWeblog_getPost(postid, username, password):
    _check(username, password)

    post = models.Entry.get_by_index(safeint(postid))

    return {
            'postid' : postid,
            'dateCreated' : post.date,
            'title' : post.title,
            'description' : unicode(post.content),
            'categories' : post.tags,
            'publish' : True,
            }

#
def metaWeblog_getRecentPosts(blogid, username, password, numberOfPosts):
    _check(username, password)

    posts, extra = models.Entry.get_posts(None, min(numberOfPosts, 30))
    result = []
    for post in posts:
        result.append({
                'postid' : str(post.index),
                'dateCreated' : post.date,
                'title' : post.title,
                'description' : unicode(post.content),
                'categories' : post.tags,
                'publish' : True,
                })

    return result
#
#
def metaWeblog_newPost(blogid, username, password, content, publish):
    _check(username, password)

    if not content.get('title') or not content.get('description'):
        raise Exception, 'invalid data.'

    author = models.RpcUser.all().filter('real_user = ', users.User(username)).get().real_user
    tags = content.get('categories')
    #datestr = content.get('dateCreated')

#    if datestr:
#        if isinstance(datestr, (str,unicode)):
#            date = parse_iso(datestr)
#        else:
#            date = parse_iso(str(datestr))
#    else:
#        date = None

    p = models.Entry.new(title=content['title'],
                    content=content['description'],
                    author=author,
                    tags=tags,
                    )
                    #date=date)
    return p.index
#
#
def metaWeblog_editPost(postid, username, password, content, publish):
    _check(username, password)

    if not content.get('title') or not content.get('description'):
        raise Exception, 'invalid data.'

#    datestr = content.get('dateCreated')
#    if datestr:
#        date = parse_iso(datestr)
#    else:
#        date = None

    p = models.Entry.get_by_index(safeint(postid))
    if p:
        tags = content.get('categories')
        p.edit(title=content['title'], content=content['description'],
                tags=tags, publish=publish)#, date=date)
        return True
    else:
        raise Exception, "Post %s doesn't exist." % postid


def metaWeblog_getCategories(postid, username, password):
    _check(username, password)
    #raise Exception('dfs')  #a tricky way to debug with client...
    tags = models.Tag.all()
    categories = []
    for tag in tags:
        categories.append({'categoryId' : tag.name,
                        'parentId':0,
                        'description':tag.name,
                        'categoryName':tag.name,
                        'htmlUrl':'',
                        'rssUrl':''
                        })
    return categories


def tublog_test(msg):
    return '%s from client.' % msg


class PlogXMLRPCDispatcher(SimpleXMLRPCDispatcher):
    def __init__(self, funcs):
        SimpleXMLRPCDispatcher.__init__(self, True, 'utf-8')
        self.funcs = funcs


dispatcher = PlogXMLRPCDispatcher({
        'blogger.getUsersBlogs' : blogger_getUsersBlogs,#
        'blogger.deletePost' : blogger_deletePost,#
        'metaWeblog.newPost' : metaWeblog_newPost,#
        'metaWeblog.editPost' : metaWeblog_editPost,
        'metaWeblog.getCategories' : metaWeblog_getCategories,#
        'metaWeblog.getPost' : metaWeblog_getPost,#
        'metaWeblog.getRecentPosts' : metaWeblog_getRecentPosts,#
        'tublog.test':tublog_test
        })
